package com.app.oral.util

import com.app.oral.dao.UserMapper
import com.app.oral.model.User
import com.app.oral.model.UserType
import com.app.oral.service.UserSessionService
import jakarta.servlet.http.HttpServletRequest
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component

/**
 * 教师权限验证工具类 - 避免在各Controller中重复权限验证代码
 */
@Component
class TeacherPermissionHelper(
    private val userSessionService: UserSessionService,
    private val userMapper: UserMapper
) {
    
    companion object {
        private val logger = LoggerFactory.getLogger(TeacherPermissionHelper::class.java)
    }
    
    /**
     * 获取当前用户信息
     */
    fun getCurrentUser(request: HttpServletRequest): User? {
        return try {
            val sessionKey = request.getHeader("Authorization")?.removePrefix("Bearer ")
                ?: throw IllegalStateException("缺少会话令牌")
            
            val session = userSessionService.validateSession(sessionKey)
                ?: throw IllegalStateException("会话无效或已过期，请重新登录")
            
            // 更新会话访问时间
            userSessionService.updateSessionAccess(sessionKey)
            
            // 获取用户详细信息
            userMapper.findById(session.userId)
        } catch (e: Exception) {
            logger.warn("获取当前用户失败: {}", e.message)
            null
        }
    }
    
    /**
     * 验证当前用户是否为教师
     */
    fun validateTeacher(request: HttpServletRequest): User? {
        val user = getCurrentUser(request) ?: return null
        
        if (user.userType != UserType.TEACHER) {
            logger.warn("非教师用户尝试访问教师接口: userId={}, userType={}", user.id, user.userType)
            return null
        }
        
        return user
    }
    
    /**
     * 验证教师是否可以访问指定班级
     */
    fun canAccessClass(teacher: User, classId: Long): Boolean {
        val teacherClassIds = teacher.getClassIdList()
        val canAccess = teacherClassIds.contains(classId)
        
        logger.debug("教师班级权限验证: teacherId={}, classId={}, teacherClasses={}, canAccess={}", 
            teacher.id, classId, teacherClassIds, canAccess)
        
        return canAccess
    }
    
    /**
     * 验证教师是否可以访问指定学生
     */
    fun canAccessStudent(teacher: User, studentUserId: Long): Boolean {
        try {
            // 获取学生信息
            val student = userMapper.findById(studentUserId)
            if (student == null) {
                logger.warn("学生不存在: studentId={}", studentUserId)
                return false
            }
            
            // 验证学生类型
            if (student.userType != UserType.STUDENT) {
                logger.warn("目标用户不是学生: userId={}, userType={}", studentUserId, student.userType)
                return false
            }
            
            // 验证学生是否在教师管理的班级内
            val studentClassIds = student.getClassIdList()
            val teacherClassIds = teacher.getClassIdList()
            
            val hasCommonClass = studentClassIds.any { it in teacherClassIds }
            
            logger.debug("教师学生权限验证: teacherId={}, studentId={}, studentClasses={}, teacherClasses={}, canAccess={}", 
                teacher.id, studentUserId, studentClassIds, teacherClassIds, hasCommonClass)
            
            return hasCommonClass
        } catch (e: Exception) {
            logger.error("验证教师学生权限失败", e)
            return false
        }
    }
    
    /**
     * 验证教师是否可以访问指定学生的练习记录
     */
    fun canAccessStudentRecord(teacher: User, studentUserId: Long, recordUserId: Long): Boolean {
        // 首先验证recordUserId是否与studentUserId一致
        if (studentUserId != recordUserId) {
            logger.warn("学生ID与记录用户ID不匹配: studentId={}, recordUserId={}", studentUserId, recordUserId)
            return false
        }
        
        return canAccessStudent(teacher, studentUserId)
    }
}